
(zhcosin/install-package-if-not-found 'restclient)


(defun restclient-to-curl ()
  "Convert current Restclient request to curl command."
  (interactive)
  (let* ((url (save-excursion
                (goto-char (point-min))
                (re-search-forward "^\\(GET\\|POST\\|PUT\\|DELETE\\) \\(.*\\)$")
                (match-string 2)))
         (method (match-string 1))
         (headers (save-excursion
                    (goto-char (point-min))
                    (let (headers)
                      (while (re-search-forward "^\\([^:]+\\): \\(.*\\)$" (save-excursion (re-search-forward "^\\s-*$") (point)) t)
                        (push (format "-H '%s: %s'" (match-string 1) (match-string 2)) headers))
                      (mapconcat 'identity headers " \\\n    "))))
         (body (if (re-search-forward "^\\s-*$" nil t)
                   (string-trim (buffer-substring (point) (point-max)))
                 "")))
    (kill-new
     (format "curl -X %s '%s' \\\n    %s%s"
             method
             url
             headers
             (if (string-empty-p body)
                 ""
               (format " \\\n    -d '%s'"  ; 不再在body内部添加续行符
                       (replace-regexp-in-string "'" "'\\\\''" body)))))
    (message "Curl command copied to clipboard!")))


(provide 'init-restclient)
